package com.onlythree.controller;

import com.alibaba.fastjson.JSONObject;
import com.onlythree.model.CorrectJsonObject;
import com.onlythree.model.ErrorJsonObject;
import com.onlythree.model.User;
import com.onlythree.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

/**
 * Created by 15c on 2018/3/9.
 */

@Controller
@RequestMapping(value = "/user")
public class UserController {
    @Autowired
    private UserService userService;

//    @ResponseBody
//    @RequestMapping(value = "/add", produces = {"application/json;charset=UTF-8"})
//    public String addUser(User user) {
//        if (user == null) {
//            return "对象为空";
//        } else {
//            int result = userService.addUser(user);
//            if (result == 1) {
//                return "添加成功";
//            } else {
//                return "添加失败";
//            }
//
//        }
//
//    }

    @ResponseBody
    @RequestMapping(value = "/add", method = RequestMethod.GET, produces = "text/html;charset=UTF-8")
    String addUser(@RequestParam(required = false) String nickname) {
        if (nickname == null || nickname.equals("")) {
            ErrorJsonObject errorJsonObject = new ErrorJsonObject(100, "昵称为空");
            return JSONObject.toJSONString(errorJsonObject);
        }
        User user = new User();
        user.setUserNickname(nickname);
        int result = userService.addUser(user);
        if (1 == result) {
            CorrectJsonObject correctJsonObject = new CorrectJsonObject("添加成功");
            return JSONObject.toJSONString(correctJsonObject);
        } else {
            ErrorJsonObject errorJsonObject = new ErrorJsonObject(101, "添加失败");
            return JSONObject.toJSONString(errorJsonObject);
        }


    }


    @ResponseBody
    @RequestMapping(value = "/all", method = RequestMethod.GET, produces = "text/html;charset=UTF-8")
    public Object findAllUser(@RequestParam(required = false) Integer pageNum, @RequestParam(required = false) Integer pageSize) {
        CorrectJsonObject correctJsonObject = new CorrectJsonObject("获取成功");
        correctJsonObject.setData(userService.findAllUser(pageNum, pageSize));
        return JSONObject.toJSONString(correctJsonObject);
    }
}
